package com.mr.cai.main.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.cai.mr.lib.utils.LogInfo;
import com.cai.mr.lib.utils.NetWorkTypeUtils;
import com.mr.cai.main.MrCaiApplication;
import com.mr.cai.main.R;
import com.mr.cai.main.activity.LoginActivity;
import com.mr.cai.main.activity.MainActivity;
import com.mr.cai.main.adapter.CartFragmentAdapter;
import com.mr.cai.main.bean.CartInfoBean;
import com.mr.cai.main.bean.CartInfoBeanList;
import com.mr.cai.main.httpApi.MrCaiHttpApi;
import com.mr.cai.main.manager.PreferencesManager;
import com.mr.cai.main.parse.CartInfoBeanListParse;
import com.mr.cai.main.utils.CommonCoreUtil;
import com.mr.cai.main.view.xlistview.XListView;

import java.util.ArrayList;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;

/**
 * Created by hai8108 on 16/2/10.
 */
public class CartPageFragment extends BaseFragment{
    private TextView titleTv;
    private XListView xListView;
    private View emptyShoppingCartView;
    private TextView toShoppingTv, toLoginTv;

    private View toChargeShoppingView;
    private CheckBox wholeCheck;
    private TextView wholePrice;
    private Button toPayBtn;

    private CartFragmentAdapter adapter;
    private ArrayList<CartInfoBean> cartInfoBeans;

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mPublicLayout = CommonCoreUtil.createPage(getActivity(), R.layout
                .fragment_page_cart_layout);
        return mPublicLayout;
    }

    @Override
    public void onViewCreated (View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findView();
        initData();
    }
    private void findView(){
        View topView = mPublicLayout.findViewById(R.id.top_view);
        topView.findViewById(R.id.pub_top_left).setVisibility(View.GONE);
        titleTv = (TextView) topView.findViewById(R.id.pub_top_mid);
        titleTv.setText(R.string.navi_cart);

        xListView = (XListView) mPublicLayout.findViewById(R.id.cart_xlist);
        xListView.setScrollable(true);
        xListView.setPullLoadEnable(false);
        xListView.setXListViewListener(ixListViewListener);
        adapter = new CartFragmentAdapter(getActivity());
        xListView.setAdapter(adapter);

        emptyShoppingCartView = mPublicLayout.findViewById(R.id.empty_cart);
        toShoppingTv = (TextView) emptyShoppingCartView.findViewById(R.id.cart_to_shopping);
        toLoginTv = (TextView) emptyShoppingCartView.findViewById(R.id.cart_to_login);

        toChargeShoppingView = mPublicLayout.findViewById(R.id.cart_to_sum);
        wholePrice = (TextView) toChargeShoppingView.findViewById(R.id.cart_sum_price);
        toPayBtn = (Button) toChargeShoppingView.findViewById(R.id.cart_to_pay_btn);
        wholeCheck = (CheckBox) toChargeShoppingView.findViewById(R.id.cart_pay_check);
    }
    private void initData(){
        if (!TextUtils.isEmpty(PreferencesManager.getInstance().getUserCustomerId())){
            toLoginTv.setVisibility(View.GONE);
        }
        CommonCoreUtil.setClickAction(toShoppingTv, new Action1() {
            @Override
            public void call (Object o) {
                ((MainActivity)getActivity()).showCurrentFragment(NaviFragmentFactory.TITLE_ENUM.HOME_ENUM);
            }
        });
        CommonCoreUtil.setClickAction(toLoginTv, new Action1() {
            @Override
            public void call (Object o) {
                LoginActivity.launchActivity(getActivity());
            }
        });
        CommonCoreUtil.setClickAction(toPayBtn, new Action1() {
            @Override
            public void call (Object o) {
                CommonCoreUtil.showToast("to pay!");
            }
        });
        wholeCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged (CompoundButton compoundButton, boolean b) {
                if (b) {
                    compoundButton.setBackgroundResource(R.drawable.cb_checked);
                } else {
                    compoundButton.setBackgroundResource(R.drawable.cb_unchecked);
                }
                setSelectedShoppingItem(b);
            }
        });
        wholeCheck.setChecked(true);
        requestCartListData();
    }
    private void setSelectedShoppingItem(boolean isSelectedAll){
        if(cartInfoBeans != null && cartInfoBeans.size()>0){
            int size = cartInfoBeans.size();
            for (int i = 0; i < size; i++) {
                cartInfoBeans.get(i).setChecked(isSelectedAll);
            }
            adapter.notifyDataSetChanged();
        }
    }
    private XListView.IXListViewListener ixListViewListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh(XListView view) {
            if (!NetWorkTypeUtils.isNetAvailable(MrCaiApplication.getInstance())) {
                requestCartListData();
            }else{
                xListView.stopRefresh();
                CommonCoreUtil.showToast(R.string.public_loading_net_null_err_txt);
            }
        }
        @Override
        public void onLoadMore(XListView view) {
        }
    };


    private Subscription cartSubscription;

    private void requestCartListData () {
        Observable<CartInfoBeanList> authCodeObservable = MrCaiHttpApi.requestCartList
                (MrCaiApplication.getInstance().getCustomerId(), new CartInfoBeanListParse());
        cartSubscription = authCodeObservable.observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call () {
                        mPublicLayout.loading(true);
                    }
                })
                .subscribe(new Subscriber<CartInfoBeanList>() {
                    @Override
                    public void onCompleted () {
                        mPublicLayout.finish();
                        mPublicLayout.finish();
                        xListView.stopLoadMore();
                        xListView.stopRefresh();
                    }
                    @Override
                    public void onError (Throwable e) {
                        mPublicLayout.dataError(false);
                        mPublicLayout.finish();
                        xListView.stopLoadMore();
                        xListView.stopRefresh();
                    }
                    @Override
                    public void onNext (CartInfoBeanList mCartInfoBeanList) {
                        if(mCartInfoBeanList.isResult() && mCartInfoBeanList.getCode() == 1){
                            cartInfoBeans = mCartInfoBeanList.getData();
                            LogInfo.log("haitian", "groupInfoBeans.size =" + cartInfoBeans.size());
                            adapter.setList(cartInfoBeans);
                            if(cartInfoBeans.size() > 0) {
                                xListView.setVisibility(View.VISIBLE);
                                toChargeShoppingView.setVisibility(View.VISIBLE);
                                emptyShoppingCartView.setVisibility(View.GONE);
                            } else {
                                xListView.setVisibility(View.GONE);
                                toChargeShoppingView.setVisibility(View.GONE);
                                emptyShoppingCartView.setVisibility(View.VISIBLE);
                            }
                        } else {
                            mPublicLayout.dataNull(mCartInfoBeanList.getMsg());
                        }
                    }
                });
    }

    @Override
    public void onDestroy () {
        super.onDestroy();
        if (cartSubscription != null) {
            cartSubscription.unsubscribe();
            cartSubscription = null;
        }
    }
}
